'''
    WeiboUser's methods
'''

import types
from WeiboClient import WeiboClient
from conf import *
from WeiboAcc import WeiboAcc
from FollowerUser import FollowerUser
from FollowersRelationship import FollowersRelationship
from MySqlDBHandle import MySqlDBHandle

class WeiboUser(WeiboClient):
    mAPI = 'users/show'
    mFollowerIdList = []

    def __init__(self, iUid, iLUTableName, iRelationshipTableName):
        self.mUid = iUid
        self.mLUTableName = iLUTableName
        self.mRelationshipTableName = iRelationshipTableName
        
        WeiboClient.__init__(self)

    def _WeiboUserAPIProcess(self):
        lParams = {}
        lParams['uid'] = self.mUid
        lParams['access_token'] = self.mPublicToken[1]
        
        print ("Get User's profile where userId = %s ..." % self.mUid)
        
        lJsonResult = self.fetchUsingAPI(self.mAPI, lParams)
        
        print ("Get User's profile success !!!")
        
        self.mJsonData = lJsonResult
        if type(lJsonResult) == types.DictType and not lJsonResult.has_key('error'):
            self._InsertWeiboAccToDB()
            
    def _InsertWeiboAccToDB(self):
        
        print ("Insert Weibo profile into WeoAcc Table ...")
        
        iSingleWeiboAccData = {}
        iSingleWeiboAccData['id'] = self.mJsonData['id']
        iSingleWeiboAccData['screen_name'] = self.mJsonData['screen_name']
        iSingleWeiboAccData['name'] = self.mJsonData['name']
        iSingleWeiboAccData['followers_count'] = self.mJsonData['followers_count']
        iWeiboAccData = []
        iWeiboAccData.append(iSingleWeiboAccData)
        weiboAccObj = WeiboAcc(iWeiboAccData)
        weiboAccObj.process()
        
        print ("Insert Weibo profile success")
   
      
    def _getUserIdInLUTable(self):
        lSQLStatement = ("SELECT (id) FROM " + self.mLUTableName + " WHERE WeiboID = %s;") % self.mUid
        try:
            result =  MySqlDBHandle.execSqlStatement(lSQLStatement)
            return result
        except Exception, e:
            print "Error when GetUserId from " + self.mLUTableName + "with weiboId = " + self.mUid 
            return None
        
    def _InsertFollowersToDB(self):
        lFollowerUser = FollowerUser(self.mUid)
        lFollowerUser.process()
        self.mFollowerIdList = lFollowerUser.getFollowersList()
        
        if type(self.mFollowerIdList) == types.ListType and len(self.mFollowerIdList) > 0:
            id = self._getUserIdInLUTable()[0][0];
            if id is None:
                return
            else:
                lFollowersRelationship = FollowersRelationship(self.mRelationshipTableName, id, self.mFollowerIdList)
                lFollowersRelationship.process()
            
        
